//20121218

/****
 * @author Tim_Lang
 * @since 2012-11-20
 */
/**
   	 * 当有自提的配送方式时，会员切换配送方式时，要刷新购物车中的商品列表和总金额，以计算或不计算存酒费
   	 */
function updateOrderSum() {
		var sumElm = $('#order_sum');
		sumElm.load(sumElm.attr('data-url'), {_:new Date().getTime()});
	}
function hasZitiSendTypeUpdateCartGoodsList()
    {
    	//有自提的配送方式
		var urlForUpdateGoodsList="/neworder/getCartGoodsList.jspa";
		var goodsListDiv=$('#cartGoodsListToUpdate');
    	var sendType=$(".order_send_type_tab .on").attr('order_type');// 配送方式
    		
		//要传的参数:自提时间
    	var dateElm = $('#ziti_date_form input.txt-datepicker');
		var params = {
				'sendType':sendType,
				'hkZitiAddressDTO.id':$('#hkZitiAddressDTO_id').val(),
                'hkZitiDateDTO.dateString':$('#ziti_date_form input.txt-datepicker').val(),
                'hkZitiDateDTO.time':$('#sel-time-select').val()
            };
		//var box=$("#showsub_aaa");//切换配送方式时显示的进度条
		var box=new LightBox("showsub_aaa");
		
		
		$.ajax({
            url: urlForUpdateGoodsList,
			dataType : "html",
			data:params,
			async:true,
			beforeSend: function(xhr)
			{
				box.Center="true";
				box.Fixed="true";	
				box.Show();
			},
			success: function(json) {
				$('#cartGoodsListToUpdate').html('');
				$('#cartGoodsListToUpdate').html(json);
				updateOrderSum();//更新订单的总金额、抵扣
			},
			complete: function(event, jqXHR, ajaxOptions)
			{
				box.Close();
			}
		
        });	
    	
    }

(function($) {	
	$.validator.setDefaults({ ignore: '' });
	
    var areaMenu = {
    		'p': 'state-trigger',
            'c': 'city-trigger',
            'd': 'district-trigger'
    };
    
    var invoiceType = {
    		'-1': '不需要发票',
    		'0': '普通发票',
    		'1': '增值税发票'
    };

    YM.namespace('YM.writeOrder.validate.regex');
    YM.writeOrder.validate.regex = {
    		expression: {
    			isMobile: function(mobile){
        			return /^1\d{10}$/.test(mobile);
        		},
        		isZip: function(zip){
        			return !zip || /^[1-9]\d{5}$/.test(zip);
        		},
        		isTelDistrictCode: function(telDCode){
        			return /^\d{1,4}$/.test(telDCode);
        		},
        		isTelCode: function(){
        			return (!$('#address-tel-d').val() && !$('#address-tel').val()) || /^\d{1,4}$/.test($('#address-tel-d').val()) && /^\d{1,8}$/.test($('#address-tel').val());
        		},
        		isFullTel: function(tel){
        			return /^\d{1,4}-\d{1,8}$/.test(tel);
        		},
        		isPositiveIntegerBy20Bytes: function(num){
        			return /^[1-9]\d{0,19}$/.test(num);
        		},
        		isPositiveInteger: function(num){
        			return /^[1-9]\d*$/.test(num);
        		},
        		isNotNegativeInteger: function(num){
        			return /^[0-9]\d*$/.test(num);
        		},
        		isArea: function(){
        			return !!$('#hidden-area').val();
        		},
        		integralDivideBy100: function(value){
        			if(!value) return false;
        			return value % 100 == 0;
        		},
        		normalInvoiceTitle: function(title){
        			if($('input[name=invoice_title_type]:checked').val()==='2'){
        				var length = $('input[name=invoice_title]').val().length;
        				return length>0 && length <=50;
        			}
        			return true;
        		}
    		},
    		init: function(){
    			var _this = this;
    			$.validator.addMethod('isMobile', function(value, element){
    		    	return _this.expression.isMobile(value);
    			}, '请输入正确的手机号！');
    			$.validator.addMethod('isZip', function(value, element){
    		    	return _this.expression.isZip(value);
    			}, '请输入正确的邮编！');
    			$.validator.addMethod('isTelDistrictCode', function(value, element){
    		    	return _this.expression.isTelDistrictCode(value);
    			}, '请输入正确的电话区号！');
    			$.validator.addMethod('isTelCode', function(value, element){
    		    	return _this.expression.isTelCode(value);
    			}, '请输入正确的电话号码！');
    			$.validator.addMethod('isFullTel', function(value, element){
    		    	return _this.expression.isFullTel(value);
    			}, '请输入正确的电话号码！');
    			$.validator.addMethod('isPositiveIntegerBy20Bytes', function(value, element){
    		    	return _this.expression.isPositiveIntegerBy20Bytes(value);
    			}, '必须为正整数且不能大于20位！');
    			$.validator.addMethod('isPositiveInteger', function(value, element){
    		    	return _this.expression.isPositiveInteger(value);
    			}, '必须为正整数！');
    			$.validator.addMethod('isNotNegativeInteger', function(value, element){
    		    	return _this.expression.isNotNegativeInteger(value);
    			}, '必须为非负整数！');
    			$.validator.addMethod('isArea', function(value, element){
    		    	return _this.expression.isArea(value);
    			}, '请输入地区！');
    			$.validator.addMethod('integralDivideBy100', function(value, element){
    		    	return _this.expression.integralDivideBy100(value);
    			}, '积分必须为100的倍数！');
    			$.validator.addMethod('normalInvoiceTitle', function(value, element){
    		    	return _this.expression.normalInvoiceTitle(value);
    			}, '请输入公司名并小于50个中文字符！');
    		}
    };
    
    
    
    YM.namespace('YM.page.writeOrder');

    YM.page.writeOrder = {
        init: function () {
        	updateOrderSum();
            initAreaSelector();
            initAddressForm();
            initAddressList();
            initZitiList();
            initOrderClearing();
        },
        resetAddressForm: function () {
        	$('#address-form-div').append($('#address-form')); //为了避免地址列表重新加载后，form消失。
            $('#address-form')[0].reset();
            $('#address-form :hidden').val('');
            $('#address-form #area-component a').attr('areaId','').html('请选择...<b></b>');
//            $('#address-form').validate().resetForm(); //此reset有严重bug,导致再次验证失效
            $('#address-form span.error').empty();
            $('#send_type_normal .ord_address_adsWrite').hide();
            return this;
        },
        closeAddressForm: function(){
        	$('#address-form-div').hide();
        	return this;
        },
        openAddressForm: function(){
        	$('#address-form-div').show();
        	return this;
        },
        closeVATFormAndReset: function(){
        	$('#vat-form-div').hide();
        	$('#vat-form-div')[0].reset();
        }
    };

    function ajaxCallback(data, func, button){
    	if(data.flag){
    		func.call(this);
    	}else{
    		var errorTip = '<p><span class="error server">{0}</span></p>';
    		if(data.scope){
    			$('input[name='+data.scope+']').parent().after(errorTip.format(data.msg));
    		}else{
    			if(button.parent().parent().find('.server').size()==0){
    				button.parent().after(errorTip.format(data.msg));
    			}
    		}
    	}
    }
    
    function loadAddressList(){
		var listElm = $('#ajax-address-list');
		listElm.load(listElm.attr('data-url'), {_:new Date().getTime()});
    }
	
    function loadZitiList(){
		var listElm = $('#ajax-ziti-list');
		listElm.load(listElm.attr('data-url'), {_:new Date().getTime()});
    }
    
    function initOrderClearing(){
    	initDeduct();
    	initInvoice();
    	initOrderRemark();
    }
    
    //发票
    function initInvoice(){
    	//获取发票信息
    	$('#invoice-deduct').live('click', function(){
    		if($(this).parent().hasClass('on')){
				if ($('#invoice-balance').html().trim()!='') return;
				$('#invoice-balance').load($('#invoice-balance').attr('data-url'), {_:new Date().getTime()}, function() {
	        		if($('#dw_radio').attr('checked')===true){
	            		$('#dw_radio').parent().next('p').show();
	            	}else{
	            		$('#dw_radio').parent().next('p').hide();
	            	}
	            	$('#dw_radio').bind('click', function(){
	            		$(this).parent().next('p').show();
	            	}).parent().parent().find('input[type="radio"]:first').bind('click', function(){
	            		$(this).parent().next().next().hide();
	            	});
	        	});
    		}
    	});
    	
    	initNormalInvoice();
    	initVATInvoice();
    }
    
    //抵扣
    function initDeduct(){
    	initAccountDeduct();
    	initIntegralDeduct();
    	initGiftCardDeduct();
    }
    
    //普通发票
    function initNormalInvoice(){
    	
    	//确认普通发票
    	$('#normal-invoice-sumbit').live('click', function(){
    		var _this = $(this);
    		var validation = $('#normal-invoice-form').validate({
    			errorElement: 'span',
        		errorClass:'error ml10',
        		errorPlacement: function(error, element){
        			element.parent("li").find("span.error").remove();
        			if(element.attr('name')!='invoice_title'){
        				error.insertAfter(element.parent().siblings('label'));
        			}else{
        				error.insertAfter(element);
        			}
        		},
	    		rules: {
	    			invoice_title_type: {
	    				required: true
	    			},
	    			invoice_content_type: {
	    				required: true
	    			},
	    			invoice_title: {
	    				normalInvoiceTitle: true
	    			}
	    		},
	    		messages: {
	    			invoice_title_type: {
	    				required: '请确认发票抬头！'
	    			},
	    			invoice_content_type: {
	    				required: '请确认发票内容！'
	    			},
	    			invoice_title: {
	    				required: '请输入单位名称'
	    			}
	    		}
    		}).form();
    		
    		if(validation){
	    		var postParams = {
	    				'key': 'invoice',
	        			'wt': 'json',
	    				'invoice_content_type': $('#normal-invoice-form input[name=invoice_content_type]:checked').val(),
	    				'invoice_title_type': $('#normal-invoice-form input[name=invoice_title_type]:checked').val(),
	    				'invoice_type': '0'
	    		};
	    		if(postParams.invoice_title_type === '2'){
	    			postParams['title'] = $('#normal-invoice-form input[name=invoice_title]').val();
	    		}
	    		$.ajax({
	        		url: '/neworder/updateDeduction.jspa',
	        		type: 'POST',
	        		cache : false,
	        		data: postParams,
	        		success: function(data){
	        			ajaxCallback(data, function(){
	        				$('#order_invoice_type').val(data.type);
	        				$('#invoice-deduct').html(invoiceType[data.type]+'<b></b>').parent().removeClass('on');
	        			}, _this);
	        		},
	                error: function () {
	                    YM.page.alert('系统发生错误，请联系网站管理员');
	                }
	        	});
    		}
    		return false;
    	});
    }
    
    //增值税发票
    function initVATInvoice(){
    	//loadVATInfo(); TODO 可以删掉
    	
    	//打开修改增税表单
    	$('#edit-vat-info').live('click', function(){
    		$('#vat-info-div').hide();
    		$('#vat-form-div').show();
    	});
    	
    	//打开修改普通发票表单
    	$('#normal-invoice-edit').live('click', function(){
    		$('#normal-invoice-info').hide();
    		$('#normal-invoice-form').show();
    	});
    	
    	//保存增税信息
    	$('#save-vat-info').live('click', function(){
    		var _this = $(this);
    		var validation = $('#vat-form').validate({
        		errorElement: 'span',
        		errorClass:'error ml10',
	    		rules: {
	    			name: {
	    				required: true,
	    				maxlength: 50
	    			},
	    			address: {
	    				required: true,
	    				maxlength: 50
	    			},
	    			phone: {
	    				isFullTel: true
	    			},
	    			bank: {
	    				required: true,
	    				maxlength: 50
	    			},
	    			bankNo: {
	    				isPositiveIntegerBy20Bytes: true
	    			},
	    			rateNo: {
	    				isPositiveIntegerBy20Bytes: true
	    			}
	    		},
	    		messages: {
	    			name: {
	    				required: '请输入发票抬头！',
	    				maxlength: '发票抬头不能超过50个中文字符！'
	    			},
	    			address: {
	    				required: '请输入寄送地址！',
	    				maxlength: '寄送地址不能超过50个中文字符！'
	    			},
	    			bank: {
	    				required: '请输入开户行！',
	    				maxlength: '开户行不能超过50个中文字符！'
	    			}
	    		}
	    		
	    	}).form();
    		
    		if(validation){
    			$.ajax({
            		url: '/neworder/updateDeduction.jspa',
            		type: 'POST',
            		cache : false,
            		data: {
            			'key': 'invoice',
            			'wt': 'json',
            			'invoice_type': '1',
            			'name': $('#vat-form input[name=name]').val(),
            			'address': $('#vat-form input[name=address]').val(),
            			'phone': $('#vat-form input[name=phone]').val(),
            			'bank': $('#vat-form input[name=bank]').val(),
            			'bankNo': $('#vat-form input[name=bankNo]').val(),
            			'rateNo': $('#vat-form input[name=rateNo]').val()
            		},
            		success: function(data){
            			ajaxCallback(data, function(){
            				$('#order_invoice_type').val(data.type);
            				$('#invoice-deduct').html(invoiceType[data.type]+'<b></b>').parent().removeClass('on');
            			}, _this);
            		},
                    error: function () {
                        YM.page.alert('系统发生错误，请联系网站管理员');
                    }
            	});
    		}
    		
    	});
    }
    
    function loadVATInfo(){
    	$('#vat-menu').bind('click', function(){
//    		$.get('/neworder/getVATInfo.jspa', function(data){
//        		$('#vat-info-div').html(data).show();
//        	});
    	});
    }
    
    //订单备注字数限制
    function initOrderRemark(){
    	var remark = $('#order-remark');
    	remark.live('keyup', function(){
    		var _this = $(this);
    		if(_this.val().getByteLength()>40){
    			_this.val(_this.val().subByte(40));
    			if(_this.parent().find('.server').size()<1){
    				_this.after('<p><span class="error ml10 server">最多可输入20个中文字符！</span></p>');
				  setTimeout(function(){
	    		    	_this.parents().find('.server').remove();
	    		  }, 3000);
    			}
        		return false;
        	}
    	});
    }
    
    //账户抵扣
    function initAccountDeduct(){
    	//获取账户余额
    	$('#account-deduct').live('click', function(){
    		if($(this).parent().hasClass('on')){
	    		$.get('/neworder/getDeduction.jspa?key=account&wt=json&time='+new Date(), function(data){
	        		$('#account-balance').html(data.account);
	        	});
    		}
    		$('#account-deduct').hasClass('true') ? $('#cancel-deduct').show() : $('#cancel-deduct').hide();
    	});
    	
    	//确认账户抵扣
    	$('#submit-deduct').live('click', function(){
    		var _this = $(this);
    		var validation = $('#account-deduct-form').validate({
    			errorElement: 'span',
        		errorClass:'error',
	    		rules: {
	    			accountDeductTotal: {
	    				required: true,
	    				isPositiveInteger: true
	    			},
	    			accountDeductPwd: {
	    				required: true
	    			}
	    		},
	    		messages: {
	    			accountDeductTotal: {
	    				required: '请输入需要抵扣的金额！',
	    				isPositiveInteger: '抵扣金额不能有小数或负数！'
	    			},
	    			accountDeductPwd: {
	    				required: '请输入支付密码！'
	    			}
	    		}
    		}).form();
    		if(validation){
	    		$.ajax({
	    			url: '/neworder/updateDeduction.jspa',
	    			 data: {
	    				'wt': 'json',
	    				'key': 'account',
	    				'amount': $('#account-deduct-total').val(),
	    				'password': $('#account-deduct-pwd').val()
	    			 },
	    			 type: 'POST',
	    			 cache : false,
	                 beforeSend: function () {},
	                 success: function (data) {
	                	 ajaxCallback(data, function(){
	                		 $('#account-deduct').addClass('true').parent().removeClass('on');
	                		 $('#account-deduct-text').html("&yen;"+data.pay).addClass('red');
	                		 $('#factual-balance').html(data.amount);
	                		 $('#account-deduct-form')[0].reset();
	                	 }, _this);
	                 },
	                 error: function () {
	                     YM.page.alert('系统发生错误，请联系网站管理员');
	                 }
	    		});
    		}
    		return false;
    	});
    	
    	//取消账户抵扣
    	$('#cancel-deduct').live('click', function(){
    		var _this = $(this);
    		$.ajax({
    			url: '/neworder/cancelDeduction.jspa',
    			 data:{
    				 'wt': 'json',
    				 'key': 'account'
    			 },
    			 type: 'POST',
    			 cache : false,
                 beforeSend: function () {},
                 success: function (data) {
                	 ajaxCallback(data, function(){
	            		 $('#account-deduct').removeClass('true').parent().removeClass('on');
	            		 $('#account-deduct-text').html("&yen;"+data.pay).removeClass('red');
                		 $('#factual-balance').html(data.amount);
                		 $('#account-deduct-form')[0].reset();
                	 }, _this);
                 },
                 error: function () {
                     YM.page.alert('系统发生错误，请联系网站管理员');
                 }
    		});
    		return false;
    	});
    }
    
    //积分抵扣
    function initIntegralDeduct(){
    	
    	//获取积分信息
    	$('#integral-deduct').live('click', function(){
    		if($(this).parent().hasClass('on')){
	    		$.get('/neworder/getDeduction.jspa?key=integral&wt=json&time='+new Date(), function(data){
	        		$('#integral-total-text').html(data.score);
	        		$('#integral-avalible-text').html(data.amount);
	        	});
    		}
    		$(this).parent().hasClass('true') ? $('#cancel-integral').show() : $('#cancel-integral').hide();
    			
    	});
    	
    	//确认积分抵扣
    	$('#submit-integral').live('click', function(){
    		var _this = $(this);
    		var validation = $('#integral-deduct-form').validate({
    			errorElement: 'span',
        		errorClass:'error',
	    		rules: {
	    			integralScore: {
	    				required: true,
	    				integralDivideBy100: true
	    			}
	    		},
	    		messages: {
	    			integralScore: {
	    				required: '请填写需抵扣的积分数'
	    			}
	    		}
    		}).form();
    		if(validation){
	    		$.ajax({
	    			url: '/neworder/updateDeduction.jspa',
	    		     data:{
	    		    	'key': 'integral',
	    		    	'wt': 'json',
	    		    	'score': $('#integral-score').val()
	    		     },
	    			 type: 'POST',
	    			 cache : false,
	                 beforeSend: function () {},
	                 success: function (data) {
	                	ajaxCallback(data, function(){
	                		 $('#integral-deduct-text').html("&yen;"+data.pay).addClass('red');
	                		 $('#integral-deduct').parent().removeClass('on').addClass('true');
	                		 $('#factual-balance').html(data.amount);
	                		 $('#integral-deduct-form')[0].reset();
	                	}, _this);
	                 },
	                 error: function () {
	                     YM.page.alert('系统发生错误，请联系网站管理员');
	                 }
	    		});
    		}
    		return false;
    	});
    	
    	//取消积分抵扣
    	$('#cancel-integral').live('click', function(){
    		var _this = $(this);
    		$.ajax({
    			 url: '/neworder/cancelDeduction.jspa',
    			 data: {
    				 'wt': 'json',
    				 'key': 'integral'
    			 },
    			 type: 'POST',
    			 cache : false,
                 beforeSend: function () {},
                 success: function (data) {
                	ajaxCallback(data, function(){
                		$('#integral-deduct-text').html("&yen;"+data.pay).removeClass('red');
                		$('#integral-deduct').parent().removeClass('on').removeClass('true');
	               		$('#factual-balance').html(data.amount);
	               		$('#integral-deduct-form')[0].reset();
                	}, _this);
                   
                 },
                 error: function () {
                     YM.page.alert('系统发生错误，请联系网站管理员');
                 }
    		});
    		return false;
    	});
    	
    }
    
    function initGiftCardDeduct(){
    	//新礼品卡
    	$('#new-giftCard-submit').live('click', function(){
    		var _this = $(this);
    		var validation = $('#new-giftCard-deduct-form').validate({
    			errorElement: 'span',
        		errorClass:'error',
	    		rules: {
	    			newGiftCardCode: {
	    				required: true,
	    				isNotNegativeInteger: true
	    			},
	    			newGiftCardPwd: {
	    				required: true
	    			}
	    		},
	    		messages: {
	    			newGiftCardCode: {
	    				required: '请输入礼品卡卡号！',
	    				isNotNegativeInteger: '礼品卡号格式错误！'
	    			},
	    			newGiftCardPwd: {
	    				required: '请输入密码！'
	    			}
	    		}
    		}).form();
    		if(validation){
	    		$.ajax({
	    			 url: '/neworder/updateDeduction.jspa',
	    			 data: {
	    				 'wt': 'json',
	    				 'key': 'giftcard',
	    				 'cardNo': $('#new-giftCard-code').val(),
	    				 'password': $('#new-giftCard-pwd').val()
	    			 },
	    			 type: 'POST',
	    			 cache : false,
	                 beforeSend: function () {},
	                 success: function (data) {
	                	ajaxCallback(data, function(){
	                		$('#giftCard-deduct').addClass('true').parent().removeClass('on');
	                		$('#giftCard-text').html('&yen;'+data.pay).addClass('red');
	                		$('#factual-balance').html(data.amount);
	                		$('#new-giftCard-deduct-form')[0].reset();
	                	}, _this);
	                 },
	                 error: function () {
	                     YM.page.alert('系统发生错误，请联系网站管理员');
	                 }
	    		});
    		}
    		return false;
    	});
    	
    	//已绑定礼品卡
    	
    	//获取已绑定礼品卡
    	$('#giftCard-deduct').live('click', function(){
    		if($(this).parent().hasClass('on')){
	    		$.get('/neworder/getDeduction.jspa?key=giftcard&time='+new Date(), function(data){
	    			$('#bind-giftCard-div').html(data);
	    		});
    		}
    	});
    	
    	//确认抵扣礼品卡
    	$('#bind-giftCard-submit').live('click', function(){
    		var _this = $(this);
    		var cardsParams = '';
    		$('.lpk_box.lpk_box_use.current p.lpk_value').each(function(){
    			cardsParams+=$(this).text()+",";
    		});
    		if(cardsParams){
	    		$.ajax({
	    			url: '/neworder/updateDeduction.jspa',
	    			 type: 'POST',
	    			 cache : false,
	    			 data: {
	    				 'wt': 'json',
	    				 'key': 'giftcard',
	    				 'cards': cardsParams.substring(0, cardsParams.length - 1)
	    			 },
	                 beforeSend: function () {},
	                 success: function (data) {
	                   ajaxCallback(data, function(){
	                	   $('#giftCard-deduct').addClass('true').parent().removeClass('on');
	               		   $('#giftCard-text').html('&yen;'+data.pay).addClass('red');
	               		   $('#factual-balance').html(data.amount);
	                   }, _this);
	                 },
	                 error: function () {
	                     YM.page.alert('系统发生错误，请联系网站管理员');
	                 }
	    		});
    		}
    	});
    	
    	//取消抵扣礼品卡
    	$('.lpk_cancel').live('click', function(){
    		var _this = $(this);
    		$.ajax({
    			url: '/neworder/cancelDeduction.jspa',
    			 type: 'POST',
    			 cache : false,
    			 data: {
    				 'wt': 'json',
    				 'key': 'giftcard',
    				 'cardNo': _this.attr('card_no')
    			 },
                 beforeSend: function () {},
                 success: function (data) {
                   ajaxCallback(data, function(){
                	   $('#giftCard-deduct').removeClass('true').parent().removeClass('on');
               		   $('#giftCard-text').html('&yen;'+data.pay);
               		   if(data.pay<=0){
               			   $('#giftCard-text').removeClass('red');
               		   }
               		   $('#factual-balance').html(data.amount);
                   }, _this);
                 },
                 error: function () {
                     YM.page.alert('系统发生错误，请联系网站管理员');
                 }
    		});
    	});
    }
    
    function initZitiList() {
    	loadZitiList();
    }
    
    function initAddressList() {
    	//加载地址
    	loadAddressList();
    
    	//加载列表的事件
    	$('#send_type_normal .adsSel_Box').live({
    		'mouseover': function(){
        		$(this).addClass('adsSel_Box_block');
        	},
        	'mouseout': function(){
        		$(this).removeClass('adsSel_Box_block');
        	},
        	'click': function(){
        		$(this).addClass('current').siblings().removeClass('current').parents('.ads_other_con').siblings('.ads_other_con').find('div').removeClass('current');
        		//重置，关闭表单。
        		YM.page.writeOrder.resetAddressForm().closeAddressForm();
        		
        		var address_id = $(this).attr("address_id");
        		changeAddress(address_id, updateOrderSum);
        	}
    	});
    	
    	// 新建地址
    	$('#send_type_normal .adsNew').bind('click', function(){
    		var _this = $(this);
    		// 把原选中地址变为非选中,并记录
    		$("#ajax-address-list .ads_other_con .adsSel_Box").each(function(){
    			if($(this).hasClass('current'))
    				$('#checkedAddressBox').val($(this).attr("address_id"));
    			$(this).removeClass('current');
        	});
    		_this.addClass('block');
    		YM.page.writeOrder.resetAddressForm();
    		$('#new-address').append($('#address-form')).show();
    	});
    	
    	//使用其他地址
    	$('#send_type_normal .ads_other').bind('click', function(){
    		$('#ajax-address-list .hidden_address').show();
    		$(this).hide();
    	});

    	//取消新建，修改地址
    	$('#send_type_normal .ord_btnOff').bind('click', function(){
    		$('.adsNew').removeClass('block');
    		$(this).parents('.ord_address_adsWrite').hide();
    		//chrome,ff3不能rest hidden域
    		YM.page.writeOrder.resetAddressForm();
			// 恢复之前选中的地址
    		var addressBox = $('#checkedAddressBox').val();
    		if(addressBox)
    			$('#'+addressBox).addClass('current');
    		return false;
    	});
    
    	
        //修改地址-获取地址详情
        $('#send_type_normal a.modify_address').live('click', function () {
            var _this = $(this);

            $.ajax({
                url: '/neworder/getAddress.jspa?addressId=' + _this.attr('addressId'),
                method: 'GET',
                cache: false,
                beforeSend: function () {
                	 YM.page.writeOrder.resetAddressForm();
                },
                success: function (data) {
                    var vo = data.memberAddress;
                    $('#address-id').val(vo.addressId);
                    $('#address-name').val(vo.name);
                    $('#address-mobile').val(vo.mobile);
                    $('#address-address').val(vo.address);
                    $('#address-zip').val(vo.zipCode);
                    
                    //电话特殊处理
                    if (vo.phone) {
                        var spiltedPhone = vo.phone.split('-');
                        $('#address-tel-d').val(spiltedPhone[0]);
                        $('#address-tel').val(spiltedPhone[1]);
                    }
                    
                    //地区
                    var areaVo = data.area;
                    $('#state-trigger').attr('areaId', areaVo.A1ID).html(areaVo.A1NAME+"<b></b>");
                    $('#city-trigger').attr('areaId', areaVo.A2ID).html(areaVo.A2NAME+"<b></b>");
                    $('#district-trigger').attr('areaId', areaVo.A3ID).html(areaVo.A3NAME+"<b></b>");
                    //地址的隐藏域
                    $('#hidden-area').val(areaVo.A3ID).keyup();
                    
                    var remainder = _this.attr('remainder') == 0 ? 4 : _this.attr('remainder');
                    _this.parents('.adsSel_Box').nextAll('.ord_address_adsWrite:first').append($('#address-form')).show().find('.pop_ads_icon').css('left', (remainder-1)*230+102);
//                    YM.page.writeOrder.openAddressForm();
                   
                },
                error: function () {
                    YM.page.alert('系统发生错误，请联系网站管理员');
                }
            });
            return false;
        });

        //删除地址
        $('#send_type_normal a.delete_address').live('click', function () {
        	$.ajax({
        		url: '/neworder/deleteAddress.jspa',
        		type: 'POST',
        		cache : false,
        		data: {
        			'addressId':  $(this).attr('addressId')
        		},
        		beforeSend: function(){
        			YM.page.writeOrder.resetAddressForm();
        		},
        		success: function(data){
        			if(data.flag){
        				//YM.page.alert('删除地址成功！');
        				
            			loadAddressList();
        				        				
            			updateOrderSum();
        			}else{
        				YM.page.alert(data.msg);
        			}
        		},
                error: function () {
                    YM.page.alert('系统发生错误，请联系网站管理员');
                }
        		
        	});
        	return false;
        });
        //设为默认地址
        $('#send_type_normal a.default_address').live('click', function () {
        	var addressId = $(this).attr('addressId');
        	$.ajax({
        		url: '/personalCenter/updateDefalutAddress.jspa',
        		type: 'POST',
        		cache : false,
        		data: {
        			'addressId': addressId
        		},
        		beforeSend: function(){
        			YM.page.writeOrder.resetAddressForm();
        		},
        		success: function(){
        			changeAddress(addressId, function() {
        				loadAddressList();
	        			updateOrderSum();
					});
        		},
                error: function () {
                    YM.page.alert('系统发生错误，请联系网站管理员');
                }
        		
        	});
        	return false;
        });
    }

    function initAddressForm() {
        $('#save-address').bind('click', function () {
        	var _this = $(this);
        	var validation = $('#address-form').validate({
        		errorElement: 'span',
        		errorClass:'error ml10',
	    		rules: {
	    			addressName: {
	    				required: true,
	    				maxlength: 40
	    			},
	    			addressMobile: {
	    				required: true,
	    				isMobile: true
	    			},
	    			addressAddress: {
	    				required: true,
	    				maxlength: 100
	    			},
	    			addressZip: {
	    				isZip: true
	    			},
	    			addressTel: {
	    				isTelCode: true
	    			},
	    			hiddenArea: {
	    				isArea: true
	    			}
	    		},
	    		messages: {
	    			addressName: {
	    				required: '请输入姓名！',
	    				maxlength: '姓名不能超过20个中文字符！'
	    			},
	    			addressMobile: {
	    				required: '请输入手机！'
	    			},
	    			addressAddress: {
	    				required: '请输入详细地址！',
	    				maxlength: '地址不能超过50个中文字符！'
	    			}
	    		}
	    		
	    	}).form();
        	if(validation){
        		var url = "/neworder/addAddress.jspa";
                var postdata = {
            		'memberAddress.name': $('#address-name').val(),
                    'memberAddress.mobile': $('#address-mobile').val(),
                    'memberAddress.areaId': $('#district-trigger').attr('areaId'),
                    'memberAddress.address': $('#address-address').val(),
                    'memberAddress.zipCode': $('#address-zip').val()
                };
                if(($('#address-tel-d').val() + "-" + $('#address-tel').val()).trim()!=='-'){
                	postdata['memberAddress.phone'] = $('#address-tel-d').val() + "-" + $('#address-tel').val();
                }
                if ($('#address-id').val()) {
                    postdata['memberAddress.addressId'] = $('#address-id').val();
                    url = "/neworder/updateAddress.jspa";
                }
                $.ajax({
                    url: url,
                    data: postdata,
                    type: 'POST',
                    cache : false,
                    beforeSend: function () {

                    },
                    success: function (req) {
                    	ajaxCallback(req, function(){
                    		//重置，关闭表单
                        	YM.page.writeOrder.resetAddressForm();
                        	_this.parents('.ord_address_adsWrite').hide();
                            // 重新加载address list
                			loadAddressList();
                			
                           // YM.page.alert('保存地址成功！');
                            
                            // 重新加载结算
                			updateOrderSum();
                    	}, _this);
                    },
                    error: function () {
                        YM.page.alert('系统发生错误，请联系网站管理员');
                    }
                });
        	}
            return false;
        });
    }
   
    function initAreaSelector() {
    	
    	$('#area-component a').bind('click', function () {
            var _this = $(this);
            if (!_this.attr('isRoot') && !_this.prev('a').attr('areaId')) {
                return;
            }
            var parentId = _this.prev('a').attr('areaId');
            var partnerId = $("#shangjiaId").attr("shangjiaId");
            var url = '/neworder/getAddressNode.jspa?partnerId=' + partnerId;
            if (parentId && parentId != '0') {
                url = url+ '&addressId=' + parentId;
            }
            $.ajax({
                url: url,
                method: 'GET',
                beforeSend: function () { 
                    $('#area-selector ul').empty();
                },
                success: function (data) {
                    if (data) {
                        $('#area-selector ul').append(fomater(data));
                        $('#area-selector').css({
                            'left': _this.offset().left + "px",
                            'top': _this.offset().top +22 + "px"
                        }).show();
                    }
                    if(!_this.attr('isTail')){
                    	$('#hidden-area').val('').keyup();
                    }
                },
                error: function () {
                    YM.page.alert('系统发生错误，请联系网站管理员');
                }
            });
        });
    	
        $('#enterAddressDistrict li a').live('click', function () {
            var _this = $(this);
            var type = _this.attr('address_type');
            $('#' + areaMenu[type]).html(_this.text() + "<b></b>").attr({
                //					 'parentId': _this.attr('fatherId'),
                'areaId': _this.attr('areaId')
            }).next('a').html('请选择...<b></b>').attr('areaId', '').next('a').html('请选择...<b></b>').attr('areaId', '');

            $('#area-selector').hide();
            if (type != 'd') {
                $.ajax({
                    url: '/neworder/getAddressNode.jspa?addressId=' + $('#' + areaMenu[type]).attr('areaId')+"&partnerId=" + $("#shangjiaId").attr("shangjiaId"),
                    method: 'GET',
                    cache : false,
                    beforeSend: function () {
                        $('#area-selector ul').empty();
                    },
                    success: function (data) {
                        if (data.length > 0) {
                            $('#area-selector ul').append(fomater(data));
                            $('#area-selector').css({
                                'left': $('#' + areaMenu[type]).next().offset().left + "px",
                                'top': $('#' + areaMenu[type]).next().offset().top + 22 + "px"
                            }).show();
                        }
                    },
                    error: function () {
                        YM.page.alert('系统发生错误，请联系网站管理员');
                    }
                });
            }else{
            	$('#hidden-area').val('1').keyup();
            }
        });
        
        //地区选择框的鼠标隐藏和显示
        $('#enterAddressDistrict').bind({
        	'mouseleave': function(){
        		$('#area-selector').hide();
        	},
        	'mouseenter': function(){
        		$('#area-selector').show();
        	}
        });
    }

    function fomater(data) {
        var trTpl = '<li>{0}</li>';
        var tdTpl = '<a areaId="{0}" address_type="{1}" style="{3}">{2}</a>';
        var tempTds = '';
        var tempTrs = '';
        var temp = '';
        for (var i = 1; i <= data.length; i++) {
            var area = data[i - 1].data;
            tempTds += tdTpl.format(area.id, area.level, area.name, "color:"+area.style);
            if (i != 0 && i % 4 == 0) {
                tempTrs = trTpl.format(tempTds);
                temp += tempTrs;
                tempTds = '';
                tempTrs = '';
            } else if (i == data.length) {
                tempTrs = trTpl.format(tempTds);
                temp += tempTrs;
            }
        }
        return temp;
    }

    // 提交订单
    function submitOrder(){
        $(".confirm_order").live('click', function(){
        	var type = $("#order_cart_type").val();

        	// 配送方式
        	$(".order_send_type_tab .on").each(function(){
        		$('#order_send_type').val($(this).attr('order_type'));
        	});
        	
        	// 配送地址
        	$("#order_address_id").val("");
        	$("#ajax-address-list .ads_other_con .current").each(function(){
        		$("#order_address_id").val($(this).attr("address_id"));
        	});
        	
        	var send_type = $('#order_send_type').val();
        	if("ORDER_TYPE_ZITI"!=send_type && 'virtual'!=type && $("#order_address_id").val()=="" && 'ORDER_TYPE_CELLAR'!=send_type){
        		YM.page.alert("请选择并确认收货地址信息！");
        		window.location.hash = "newAds-P";
        		return;
        	}
        	
        	//配送时间
    		$(".ads_time_sel input").each(function(){
    			if(this.checked)
    				$("#order_send_date_type").val($(this).val());
    		});

    		if('ORDER_TYPE_CELLAR'==send_type){

    			if($('input[type="radio"][name="type_cellar"]:checked').size()<=0){ 
    				YM.page.alert('您未选择存酒库！');
    				return;
    			}
    			if($('input[type="checkbox"][name="type_cellar_xy"]:checked').size()<=0){
    				YM.page.alert("您未接受用户协议");
    				return;
    			}
    			changeAddress(-9999);
    			$("#order_address_id").val(-9999);
    		}
    		if("ORDER_TYPE_ZITI"==send_type){
    			//如果是自提的，要验证自提人、自提时间
    			if($('#hkZitiAddressDTO_id').val()=="")
    			{
    				YM.page.alert('请填写自提人信息！');
    				return;	
    			}
    			var zitiYearMonthDay=$('#sel-year-select').val()+"-"+$('#sel-month-select').val()+"-"+$('#sel-day-select').val()
    			var zitiDateNotTime = Date.parse(zitiYearMonthDay);
    			var afterSixYearDate=new Date();
    			afterSixYearDate.setDate(afterSixYearDate.getDate() + 365*6);
    			if(zitiDateNotTime>afterSixYearDate)
    			{
    				YM.page.alert('自提时间不能超出6年！');
    				return;
    			}
    			
    			changeAddress(-9998);
    			$("#order_address_id").val(-9998);
    		}
    		var url = "/neworder/goToChoosePayWay.jspa";
            var postdata = {
            	'cartType' : $("#order_cart_type").val(), // 配送类型
                'writeOrderParaDTO.addressId': $('#order_address_id').val(),
                'writeOrderParaDTO.sendType': $('#order_send_type').val(),
                'writeOrderParaDTO.sendDateType': $('#order_send_date_type').val(),
                'writeOrderParaDTO.sendRequire': $('#order-remark').val(),
                'writeOrderParaDTO.invoiceType': $('#order_invoice_type').val(),
                
                'hkZitiAddressDTO.id':$('#hkZitiAddressDTO_id').val(),
                'hkZitiDateDTO.dateString':$('#ziti_date_form input.txt-datepicker').val(),
                'hkZitiDateDTO.time':$('#sel-time-select').val()
            };
            
            $.ajax({
                url: url,
                data: postdata,
                type: 'POST',           
    			dataType : "json",	
    			url: "/neworder/goToChoosePayWay.jspa",
    			data:postdata,
    			async:false,
    			success: function(json) { 
    				  if(json.flag == 1){
    					  window.location.replace(json.nextUrl);
    					  return;
    				  }else if(json.flag == -1){ //0元订单
    					  var tokenName = $("input[name='struts.token.name']").val();
    			    	  var tokenValue = $("input[name='struts.token']").val();
    			    	  window.location.replace(json.nextUrl + "&struts.token.name="+tokenName+"&struts.token="+tokenValue);
    			    	  return;
    				  }else{
    					  YM.page.alert(json.msg);
    				  }
    			}
            });		
    	});
    }
    
    $(function () {
    	YM.writeOrder.validate.regex.init();
        YM.page.writeOrder.init();
        submitOrder();
        //消除全局的服务器端验证
        $('input.input_txt').live('focus', function(){
        	$('p span.error.server').remove();
      });		
		// 收货方式切换
		$('.address_tab li').click(function() {
			var order_type = $(this).attr('order_type');
			var old_order_type=$('.address_tab li[class*="on"]').attr("order_type");//原来选中的配送方式
			$(this).addClass('on').siblings().removeClass('on');
			$('.ord_address_con').attr('class', 'ord_address_con bd con_'+ order_type);
			//
			if (order_type=='ORDER_TYPE_CELLAR') {
				changeAddress(-9999, updateOrderSum);
			}
			else if("ORDER_TYPE_ZITI"==order_type)
			{
				changeAddress(-9998);
			}
			else {
				changeAddress($("#default_addressId").val(), updateOrderSum);
			}
			
			//自提处理，开始
			var hasSendTypeZiti=$('.address_tab li[order_type="ORDER_TYPE_ZITI"]').length
			
			if(hasSendTypeZiti>0 && ("ORDER_TYPE_ZITI"==old_order_type || "ORDER_TYPE_ZITI"==order_type))
			{
				//如果有自提的配送方式，并且这次切换是发生在自提在其它配送方式之间的，要在切换配送方式时更新商品清单，以计算存储费
				hasZitiSendTypeUpdateCartGoodsList();
			}
			
			//自提处理，结束
		});		
		//快也买(配送区域,订购指南)弹框
		$('#dg-link').click(function(){
			YM.page.dialog.pop({title:'订购指南', url:'http://www.yesmywine.com/marketing/topic/011425/011425.html',  width:900,height:394});
		});
		$('.quyu').click(function(){
			YM.page.dialog.pop({title:'配送区域', url:'http://www.yesmywine.com/marketing/topic/011424/011424.html',  width:900, height:885});
		});
    });    
    
	function changeAddress(addressId, callback) {
    	$.ajax({
    		cache : false,
    		type: "POST",
    		url: "/neworder/changeAddress.jspa",
    		data : {addressId:addressId},
    		dataType : 'json',
    		async : false,
    		success:function(json){
    			if(json.flag == 0){
    				$('#order_address_id').val(addressId);	
    			}
				if (callback) callback();
    		}
    	});
    }
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	function saveZitiData() {
		$.post('/neworder/saveHKZitiAdressAjax.jspa',{"hkZitiAddressDTO.name":$("#hkZitiAddressDTO_name").val(),"hkZitiAddressDTO.mobile":$("#hkZitiAddressDTO_mobile").val()}, function(data){
			
			var json = JSON.parse(data);
			var saveSuccess=json.success;
			
			if(saveSuccess!="1")
			{
				alert("保存失败\n"+json.msg);
			}	
			else
			{
				$("#ziti-display-name").text(json.name);
				$("#ziti-display-mobile").text(json.mobile);
				$("#hkZitiAddressDTO_id").val(json.id);
				
				$("#ziti-display-div").show();
				$("#ziti-form-div").hide();
			}
    	});
		
	}
	

	
	
	
	//保存自提人信息
	$('#saveHKZitiOK').live('click', function(){
	
		var _this = $(this);
		var validation = $('#ziti-form').validate({
			errorElement: 'span',
    		errorClass:'error ml10',
    		rules: {
    			'hkZitiAddressDTO.name': {
    				required: true
    				
    			},
    			'hkZitiAddressDTO.mobile': {
    				required: true
    				
    			}
    		},
    		messages: {
    			'hkZitiAddressDTO.name': {
    				required: '提货人必填'
    			},
    			'hkZitiAddressDTO.mobile': {
    				required:'手机必填'
    			}
    		}
		}).form();
		
		if(validation)
    	{
			saveZitiData();
    	}	
	});
	
	$(function () {
		$('.address_tab li').eq(0).click();//先选择一下配送方式  
	});    
	
})(jQuery);
